// JavaScript Document

!(function(w){	
	
	function loader(){
		
		this.all_url=[];
		
		this.index=0;
		
		this.callback=[];
		
		//head对象
		this.domHead=document.getElementsByTagName("head")[0];
		
		var _this=this;
		
		setTimeout(function(){_this.init();},10);
	}
	
	loader.prototype={
		url:function(url){
			var url=url||[""];
			
			//数组去重
			var temp=[];
			
			for(var i=0;i<this.all_url.length;i++){
				temp[this.all_url[i]]=true;
			}
			
			for(var i=0;i<url.length;i++){
				if(!temp[url[i]]){					
					this.all_url.push(url[i]);
				}
			}
			
		},
		ready:function(callback){
			this.callback.push(callback||function(){});
		},
		init:function(){
			var _this=this;
			
			!(function(){
				
				if(_this.all_url.length>0){
					
					_this.addScript(_this.all_url[0]);
					
					return;
				}
				
				window.setTimeout(arguments.callee,1);
				
			})();
	
		},
		addScript:function(url){
			
			var DOM_ELEMENT,_this=this;
			
			//如果是css文件地址
			if(/\.css/gi.test(url)){
				DOM_ELEMENT=document.createElement("link");
				DOM_ELEMENT.type="text/css";
				DOM_ELEMENT.rel="stylesheet";
				DOM_ELEMENT.href=url;	
			}
			else{
				DOM_ELEMENT=document.createElement('script');
				DOM_ELEMENT.type = 'text/javascript';
				DOM_ELEMENT.src=url;
			}
			
			if(_this.index<_this.all_url.length){
				//ie8及以下
				if(DOM_ELEMENT.readyState){
					DOM_ELEMENT.onreadystatechange = function(){
						if(DOM_ELEMENT.readyState === "loaded" || DOM_ELEMENT.readyState === "complete"){
							
							_this.eachScript(++_this.index);
							
							DOM_ELEMENT.onreadystatechange=null;
						}
					}
						
				}
				//其他浏览器
				else{
					DOM_ELEMENT.onload=function(){
						
						_this.eachScript(++_this.index);
						
						DOM_ELEMENT.onload=null;
					}	
				}
			}
			else{
				
				for(var i=0;i<this.callback.length;i++){
					
					this.callback[i].call(this);
				}
				
				return;
				
			}
			
			//把创建好的css or js 文件添加到head
			_this.domHead.appendChild(DOM_ELEMENT);
		},
		
		eachScript:function(index){
			this.addScript(this.all_url[index]);
		}
	};
	
	
	w.JSLoader = new loader();

})(window);